﻿using LF.Common;
using LF.Domain.Entities;
using LF.Domain.Helper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LF.Domain.Seed
{
    public class SystemSeedDataInitializer
    {

        private readonly ILogger<SystemSeedDataInitializer> _logger;

        public SystemSeedDataInitializer( ILogger<SystemSeedDataInitializer> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 初始化所有系统种子数据
        /// </summary>
        public void Initialize()
        {
            _logger.LogInformation("开始初始化系统种子数据");

            // 按照依赖关系顺序调用各个初始化方法
            InitializeSysAdmin();
            InitializeDictionaries();
            InitializeParamConfigs(); // 添加参数配置初始化
            // 可以添加更多初始化方法...

            _logger.LogInformation("系统种子数据初始化完成");
        }

        /// <summary>
        /// 初始化系统管理员账号
        /// </summary>
        private void InitializeSysAdmin()
        {
            _logger.LogInformation("初始化系统管理员账号");

            // 检查是否已存在sysadmin用户
            var sysAdmin = FreeSqlHelper.DbContext.Select<User>()
                .Where(u => u.UserName == "sysadmin" && !u.IsDelete)
                .First();

            if (sysAdmin != null)
            {
                _logger.LogInformation("系统管理员账号已存在，跳过初始化");
                return;
            }

            FreeSqlHelper.DbContext.Transaction(() =>
            {
                // 1. 创建系统管理员角色
                var adminRole = new Role
                {
                    Id = Guid.NewGuid(),
                    Name = "系统管理员",
                    Status = 1, // 启用
                    Remark = "系统内置管理员角色，拥有所有权限",

                };

                FreeSqlHelper.DbContext.Insert(adminRole).ExecuteAffrows();

                // 2. 创建sysadmin用户
                sysAdmin = new User
                {
                    Id = Guid.NewGuid(),
                    UserName = "sysadmin",
                    RealName = "系统管理员",
                    Mobile = "",
                    Password = "admin@123".ToFastMd5(), // 默认密码
                    Active = true,
                };

                FreeSqlHelper.DbContext.Insert(sysAdmin).ExecuteAffrows();

                // 3. 给用户分配管理员角色
                var userRole = new UserRole
                {
                    Id = Guid.NewGuid(),
                    UserId = sysAdmin.Id,
                    RoleId = adminRole.Id,
                    CreatTime = DateTime.Now,
                    UpdateTime = DateTime.Now
                };

                FreeSqlHelper.DbContext.Insert(userRole).ExecuteAffrows();
            });

            _logger.LogInformation("系统管理员账号初始化完成");
        }

        /// <summary>
        /// 初始化所有字典数据
        /// </summary>
        private void InitializeDictionaries()
        {
            _logger.LogInformation("初始化系统字典数据");

            // 初始化切片方式字典
            InitializeSliceTypeDict();

            // 这里可以添加其他字典的初始化

            _logger.LogInformation("系统字典数据初始化完成");
        }

        /// <summary>
        /// 初始化参数配置表
        /// </summary>
        private void InitializeParamConfigs()
        {
            _logger.LogInformation("初始化系统参数配置");

            // 初始化默认密码参数
            InitializeDefaultPasswordConfig();

            // 这里可以添加其他参数配置的初始化

            _logger.LogInformation("系统参数配置初始化完成");
        }

        /// <summary>
        /// 初始化默认密码参数配置
        /// </summary>
        private void InitializeDefaultPasswordConfig()
        {
            _logger.LogInformation("初始化默认密码参数配置");

            // 检查参数配置是否已存在
            var existingConfig = FreeSqlHelper.DbContext.Select<ParamConfig>()
                .Where(p => p.Key == "default_password" && !p.IsDelete)
                .First();

            if (existingConfig != null)
            {
                _logger.LogInformation("默认密码参数配置已存在，跳过初始化");
                return;
            }

            FreeSqlHelper.DbContext.Transaction(() =>
            {
                // 创建默认密码参数配置
                var defaultPasswordConfig = new ParamConfig
                {
                    Id = Guid.NewGuid(),
                    Name = "默认密码",
                    Key = "default_password",
                    Value = "Aa12345",
                    Remark = "系统默认密码，用于新建用户和重置密码",
                };

                FreeSqlHelper.DbContext.Insert(defaultPasswordConfig).ExecuteAffrows();
            });

            _logger.LogInformation("默认密码参数配置初始化完成");
        }

        /// <summary>
        /// 初始化切片方式字典
        /// </summary>
        private void InitializeSliceTypeDict()
        {
            _logger.LogInformation("初始化切片方式字典");

            // 检查字典类型是否已存在
            var existingType = FreeSqlHelper.DbContext.Select<DictType>()
                .Where(p => p.Code == "slice_type" && !p.IsDelete)
                .First();

            if (existingType != null)
            {
                _logger.LogInformation("切片方式字典已存在，跳过初始化");
                return;
            }

            FreeSqlHelper.DbContext.Transaction(() =>
            {
                // 创建字典类型
                var dictType = new DictType
                {
                    Id = Guid.NewGuid(),
                    Name = "切片方式",
                    Code = "slice_type",
                    Status = 1, // 启用
                    Remark = "知识库文件切片方式",
                };

                FreeSqlHelper.DbContext.Insert(dictType).ExecuteAffrows();

                // 创建字典项
                var dictItems = new List<DictItem>
                {
                    new DictItem
                    {
                        Id = Guid.NewGuid(),
                        Label = "固定长度",
                        Value = "0",
                        TypeId = dictType.Id,
                        OrderNo = 1,
                        Status = 1, // 启用
                        Remark = "按固定长度切片",
                    },
                    new DictItem
                    {
                        Id = Guid.NewGuid(),
                        Label = "QA问答",
                        Value = "1",
                        TypeId = dictType.Id,
                        OrderNo = 2,
                        Status = 1, // 启用
                        Remark = "按QA问答方式切片",
                    },
                    new DictItem
                    {
                        Id = Guid.NewGuid(),
                        Label = "段落",
                        Value = "2",
                        TypeId = dictType.Id,
                        OrderNo = 3,
                        Status = 1, // 启用
                        Remark = "按段落切片",
                    }
                };

                FreeSqlHelper.DbContext.Insert(dictItems).ExecuteAffrows();
            });

            _logger.LogInformation("切片方式字典初始化完成");
        }
    }
}
